package com.harmonk.firstscene.ui.model

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.harmonk.firstscene.FirstSceneApplication
import com.harmonk.firstscene.db.entity.Vehicle
import kotlinx.coroutines.launch

class VehicleViewModel(application: Application) : AndroidViewModel(application) {
    private val vehicleRepository = (application as FirstSceneApplication).vehicleRepository
    
    private val _vehicles = MutableLiveData<List<Vehicle>>()
    val vehicles: LiveData<List<Vehicle>> = _vehicles
    
    private val _currentVehicle = MutableLiveData<Vehicle>()
    val currentVehicle: LiveData<Vehicle> = _currentVehicle
    
    fun loadVehiclesByEventId(eventId: Long) {
        viewModelScope.launch {
            try {
                vehicleRepository.getVehiclesByEventId(eventId).collect { vehicleList: List<Vehicle> ->
                    _vehicles.postValue(vehicleList)
                }
            } catch (e: Exception) {
                // Handle exception
                _vehicles.postValue(emptyList())
            }
        }
    }
    
    fun getVehicleById(id: Long) {
        viewModelScope.launch {
            try {
                val vehicle = vehicleRepository.getVehicleById(id)
                vehicle?.let { v: Vehicle ->
                    _currentVehicle.postValue(v)
                }
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
    
    fun insertVehicle(vehicle: Vehicle): Long {
        var id: Long = -1
        viewModelScope.launch {
            try {
                id = vehicleRepository.insertVehicle(vehicle)
            } catch (e: Exception) {
                // Handle exception
            }
        }
        return id
    }
    
    fun updateVehicle(vehicle: Vehicle) {
        viewModelScope.launch {
            try {
                vehicleRepository.updateVehicle(vehicle)
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
    
    fun deleteVehicle(vehicle: Vehicle) {
        viewModelScope.launch {
            try {
                vehicleRepository.deleteVehicle(vehicle)
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
}

class VehicleViewModelFactory(private val application: Application) : ViewModelProvider.Factory {
    override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(VehicleViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return VehicleViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}